import {
	reactive
} from 'vue';
import CryptoJS from 'crypto-js';
import {
	JSEncrypt
} from 'encryptlong';

//访问后台地址
// export const baseUrl = 'https://www.jzerp.com/default/';
//export const baseUrl = 'http://121.40.66.58:8088/default/';
// export const baseUrl = 'http://127.0.0.1:8089/default/';
export const serveUrl = 'http://127.0.0.1:5200';
export const baseUrl = serveUrl + '/api/';

// 定义响应式状态对象
export const sharedState = reactive({
	isLogin: false,
	shipNumber: '',
});

export const groupBy = function(arr, key) {
	return arr.reduce((acc, obj) => {
		const groupKey = obj[key];
		if (!acc[groupKey]) {
			acc[groupKey] = [];
		}
		acc[groupKey].push(obj);
		return acc;
	}, {});
}

export const stringIsBlank = function(object) {
	return object === null || object === '' || object === undefined;
}

export const convertWeekDayToChinese = function(weekDay) {
	switch (weekDay) {
		case "0":
			return "星期日";
		case "1":
			return "星期一";
		case "2":
			return "星期二";
		case "3":
			return "星期三";
		case "4":
			return "星期四";
		case "5":
			return "星期五";
		case "6":
			return "星期六";
	}

}


/**
 * 发送登录请求到API
 * @param {string} username 用户名
 * @param {string} password 密码
 * @param {string} language 语言，默认为'zh-CHS'
 * @param {string} tenant 租户ID，默认为'10000'
 * @returns {uni.RequestTask} API响应数据
 */
export const signInRequest = function(username, password) {
		const formData = {
			language: "zh-CHS",
			seType: "true",
			Tenant: "10000",
			Authenstrategy: "UserPassword",
			username: username,
			password: password
		};

		return uni.request({
			url: serveUrl + "/sign-in",
			method: 'POST',
			data: formData,
			header: {
				'content-type': 'application/x-www-form-urlencoded',
			},
			redirect: 'manual',
			success({data,statusCode,header}) {

			},
			fail(err) {
				console.error('请求失败:', err);
			}
		});

};

/**
 * RSA加密
 * @param {string} content 要加密的内容
 * @param {string} publicKey 公钥
 * @returns {string} 加密后的Base64字符串
 */
export const rsaEncrypt = function(content, publicKey) {
	const encryptor = new JSEncrypt();
	encryptor.setPublicKey(publicKey);

	// 加密并返回Base64结果
	return encryptor.encryptLong(content);
}

/**
 * RSA解密
 * @param {string} encrypted 加密的Base64字符串
 * @param {string} privateKey 私钥
 * @returns {string} 解密后的原始字符串
 */
export const rsaDecrypt = function(encrypted, privateKey) {
	const decryptor = new JSEncrypt();
	decryptor.setPrivateKey(privateKey);

	return decryptor.decryptLong(encrypted);
}

/**
 * 生成RSA密钥对
 * @returns {Object} 包含公钥和私钥的对象 {publicKey, privateKey}
 */
export const generateRSAKeyPair = function() {
	const encryptor = new JSEncrypt({
		default_key_size: 2048
	});
	return {
		publicKey: encryptor.getPublicKey(),
		privateKey: encryptor.getPrivateKey()
	};
}


let formDataDefault = new Map(
	[['lanuage', 'zh-CHS'],
	['tenant-id', '10000']]
)

export const request = (url, method, data, key,queryString) => {
	let queryFormData = new Map(
		[...formDataDefault]
	)
	queryFormData.set('api-key', key)
	let urlQuery = ''
	queryFormData.forEach((v,k) => {
		urlQuery += '' + k + '=' + v + '&'
	})
	urlQuery = urlQuery.substring(0,urlQuery.length-1)
	urlQuery += queryString ? '&' + queryString : ''
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url + `?` + urlQuery, //拼接请求路径
			data: data,
			method: method,
			timeout: 30000, // 固定30秒超时
			header: {
				'content-type': 'application/json',
				'Authorization': 'Bearer',
			},
			success: (res) => {
				resolve(res)
			},
			fail: (error) => {
				reject(error)
			}
		})
	})
}

export const postRequest = function(url, params) {
	return new Promise((resolve, reject) => {
		const formData = {
			...formDataDefault,
			...params,
		};
		uni.request({
			url: baseUrl + url,
			header: {
				'content-type': 'application/json;charset=UTF-8',
			},
			data: formData,
			method: 'POST',
			success: (res) => {
				resolve(res.data);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
}


export const getUserInfo = function() {
	if (isBankObj(uni.getStorageSync("user_info"))) {
		uni.reLaunch({
			url: "/pages/login/login"
		})
		uni.showToast({
			title: '登录失效，请重新登录！',
			icon: 'none'
		});
	} else {
		return uni.getStorageSync("user_info");
	}
}

export const getUserId = function() {
	return uni.getStorageSync("user_info").id;
}
export const getUserName = function() {
	return uni.getStorageSync("user_info").name;
}


export const removeUserInfo = function() {
	return uni.removeStorage({
		key: 'user_info',
		success: function(res) {
			//console.log('success');
		}
	});
}


export const isBankStr = (str) => {
	if (str === null || str === undefined || str === '') return true;
	else return false;
}

export const isBankObj = (obj) => {
	if (Object.keys(obj).length === 0) return true;
	else return false;
}

export const sortList = (array) => {
	array.sort((a, b) => {
		// 区分中英文
		const isEnglishA = /^[a-zA-Z]+$/.test(a);
		const isEnglishB = /^[a-zA-Z]+$/.test(b);

		if (isEnglishA && !isEnglishB) {
			return -1;
		} else if (!isEnglishA && isEnglishB) {
			return 1;
		}

		// 中文比较
		return a.localeCompare(b);
	});
	return array;
}

export const sortListWithKey = (array, key) => {
	array.sort((a, b) => {
		// 区分中英文
		const isEnglishA = /^[0-9a-zA-Z]+$/.test(a[key]);
		const isEnglishB = /^[0-9a-zA-Z]+$/.test(b[key]);

		if (isEnglishA && !isEnglishB) {
			return -1;
		} else if (!isEnglishA && isEnglishB) {
			return 1;
		}

		// 中文比较
		return a[key].localeCompare(b[key]);
	});
	return array;
}

export const colorList = [{}];

export const setListStyle = function(list) {
	var styleList = [];
	if (list && list.length > 0) {

		list.forEach(item => {
			//默认样式
			let textStyle = {
				color: 'gainsboro',
				background: 'grey',
				statusText: ''
			}
			//设置专业颜色
			if (item.specialty == 'CCS' || item.inspectionmajorName == 'CCS') {
				textStyle.color = '#FA9C07';
				textStyle.background = '#FFF2EA';
			}
			if (item.specialty == 'CS' || item.inspectionmajorName == 'CS') {
				textStyle.color = 'red';
				textStyle.background = '#8bc34a';
			}
			if (item.specialty == 'E' || item.inspectionmajorName == 'E') {
				textStyle.color = '#0CC07E';
				textStyle.background = '#E1F8EE';
			}
			if (item.specialty == 'H' || item.inspectionmajorName == 'H') {
				textStyle.color = '#3950C6';
				textStyle.background = '#E5EAFE';
			}
			if (item.specialty == 'HO' || item.inspectionmajorName == 'HO') {
				textStyle.color = '#488BFD';
				textStyle.background = '#EDF7FF';
			}
			if (item.specialty == 'M' || item.inspectionmajorName == 'M') {
				textStyle.color = '#3FA911';
				textStyle.background = '#E9FFD9';
			}
			if (item.specialty == 'P' || item.inspectionmajorName == 'P') {
				textStyle.color = '#D3B00C';
				textStyle.background = '#FFF3CA';
			}
			//设置状态文字说明
			//内检
			if (item.hasOwnProperty('internalStatus')) {
				if (isBankStr(item.internalStatus)) {
					textStyle.statusText = "";
				} else if (item.internalStatus == 0) {
					textStyle.statusText = "待发起";
				} else if (item.internalStatus == 1) {
					textStyle.statusText = "不合格";
				} else if (item.internalStatus == 2) {
					textStyle.statusText = "被退回";
				} else if (item.internalStatus == 3) {
					textStyle.statusText = "待反馈";
				} else if (item.internalStatus == 4) {
					textStyle.statusText = "合格";
				}

				if (item.hasOwnProperty('externalProcessStatus')) {
					if (isBankStr(item.processStatus)) {
						textStyle.statusText = "待发起";
					} else if (item.processStatus == 0) {
						textStyle.statusText = "被退回";
					} else if (item.processStatus == 1) {
						textStyle.statusText = "待预约";
					} else if (item.processStatus == 2) {
						textStyle.statusText = "待反馈";
					} else if (item.processStatus == 3) {
						textStyle.statusText = "不合格";
					} else if (item.processStatus == 4) {
						textStyle.statusText = "合格";
					}
				}
			}
			//外检
			if (item.hasOwnProperty('processStatus')) {
				if (isBankStr(item.processStatus)) {
					textStyle.statusText = "待发起";
				} else if (item.processStatus == 0) {
					textStyle.statusText = "被退回";
				} else if (item.processStatus == 1) {
					textStyle.statusText = "待预约";
				} else if (item.processStatus == 2) {
					textStyle.statusText = "待反馈";
				} else if (item.processStatus == 3) {
					textStyle.statusText = "不合格";
				} else if (item.processStatus == 4) {
					textStyle.statusText = "合格";
				}
			}
			item.textStyle = textStyle;
		})
	}
	return list;

};

/**
 * 判断是否为数组
 * @param {*} arr 
 * @returns {boolean}
 */
export const isArray = (arr) => {
	return Object.prototype.toString.call(arr) === '[object Array]';
};

/**
 * 深度克隆对象
 * @param {*} obj 
 * @returns {*}
 */
export const deepClone = (obj) => {
	// 对常见的"非"值，直接返回原来值
	if ([null, undefined, NaN, false].includes(obj)) return obj;
	if (typeof obj !== "object" && typeof obj !== 'function') {
		// 原始类型直接返回
		return obj;
	}
	const o = isArray(obj) ? [] : {};
	for (const i in obj) {
		if (obj.hasOwnProperty(i)) {
			o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i];
		}
	}
	return o;
};


/**
 * Date => String(yyyy-MM-dd HH:mm:ss) open为false时，舍去时分秒
 * @param {*} date 日期类型参数
 * @param {*} needMore 判断是否舍去时分秒
 * @param {*} needSecond 判断是否舍去秒
 * @param {*} T 判断是否加T
 * @returns 字符串类型 yyyy-MM-dd HH:mm:ss 日期格式
 */
export const FormatTimeOne = function(date, needMore, needSecond, T = " ") {
	if (date === undefined || date === null || !(date instanceof Date)) {
		console.log('FormatTimeOne函数，格式输入错误！');
		return null;
	}
	var year = date.getFullYear();
	var month = formatTime(date.getMonth() + 1);
	var day = formatTime(date.getDate());
	var hour = formatTime(date.getHours());
	var minute = formatTime(date.getMinutes());
	var second = formatTime(date.getSeconds());
	if (needMore) {
		if (needSecond) return year + "-" + month + "-" + day + T + hour + ":" + minute + ":" + second;
		else return year + "-" + month + "-" + day + T + hour + ":" + minute;
	} else return year + "-" + month + "-" + day;
}

export const formatTime = function(x) {
	//判断是否需要加0
	if (x < 10) {
		return '0' + x;
	} else {
		return x;
	}
}

/** 对象同名key赋值 
 * @param {Object} objA 被赋值
 * @param {Object} objB 赋值
 */
export const assignObjSameKeys = function(objA, objB) {
	const newObj = deepClone(objA); // 复制对象
	const oldObj = deepClone(objB); // 复制对象
	Object.keys(oldObj).forEach(key => {
		if (objA.hasOwnProperty(key)) {
			newObj[key] = oldObj[key]; // 更新新对象中与对象B相同键的值
		}
	});
	return newObj;
}

//使用原生JavaScript生成uuid
export const getUuid =
	function() {
		var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random() * 16 | 0,
				v = c === 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
		return uuid;
	}

/**
 * 普通数组 单一属性排序
 * @param {*} array 接收数组
 * @param {*} order true 从小到大 false 从大到小
 * @param {*} strOrder true => '1' '12' '2' false => '1' '2' '12' 强制String类型的数字 按Number类型排序
 */
export const arraySort = function(array, order, strOrder) {
	array.sort(compare(order, strOrder));
}

export const compare = function(order, strOrder) {
	return function(value1, value2) {
		if (order) {
			if (typeof value1 === 'string') {
				if (strOrder) {
					return value1.localeCompare(value2);
				} else {
					return value1 - value2;
				}
			} else if (typeof value1 === 'number') {
				return value1 - value2;
			} else if (typeof value1 === 'object' && value1 instanceof Date) {
				var time1 = value1.getTime();
				var time2 = value2.getTime();
				return time1 - time2;
			} else {
				return 0;
			}
		} else {
			if (typeof value1 === 'string') {
				if (strOrder) {
					return value2.localeCompare(value1);
				} else {
					return value2 - value1;
				}
			} else if (typeof value1 === 'number') {
				return value2 - value1;
			} else if (typeof value1 === 'object' && value1 instanceof Date) {
				var time1 = value1.getTime();
				var time2 = value2.getTime();
				return time2 - time1;
			} else {
				return 0;
			}
		}
	};
}
/**
 * 对象数组 单一属性排序
 * @param {*} array 接收数组
 * @param {*} property 单一属性
 * @param {*} order true 从小到大 false 从大到小
 * @param {*} strOrder true => '1' '12' '2' false => '1' '2' '12' 强制String类型的数字 按Number类型排序
 */
export const arrayObjectSortSingle = function(array, property, order, strOrder) {
	array.sort(compareObject(property, order, strOrder));
}

export const compareObject = function(property, order, strOrder) {
	return function(a, b) {
		var c = Object.keys(a);
		var index = 0;
		for (var i = 0; i < c.length; i++) {
			if (c[i] === property) {
				index = i;
			}
		}
		var value1 = objectGetValue(a)[index];
		var value2 = objectGetValue(b)[index];
		if (order) {
			if (typeof value1 === 'string') {
				if (strOrder) {
					return value1.localeCompare(value2);
				} else {
					return value1 - value2;
				}
			} else if (typeof value1 === 'number') {
				return value1 - value2;
			} else if (typeof value1 === 'object' && value1 instanceof Date) {
				var time1 = value1.getTime();
				var time2 = value2.getTime();
				return time1 - time2;
			} else {
				return 0;
			}
		} else {
			if (typeof value1 === 'string') {
				if (strOrder) {
					return value2.localeCompare(value1);
				} else {
					return value2 - value1;
				}
			} else if (typeof value1 === 'number') {
				return value2 - value1;
			} else if (typeof value1 === 'object' && value1 instanceof Date) {
				var time1 = value1.getTime();
				var time2 = value2.getTime();
				return time2 - time1;
			} else {
				return 0;
			}
		}
	};
}

export const objectGetValue = function(obj) {
	var values = [];
	for (var key in obj) {
		if (Object.prototype.hasOwnProperty.call(obj, key)) {
			values.push(obj[key]);
		}
	}
	return values;
}